package com.ruoyi.aitcommon.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import java.lang.reflect.InvocationTargetException;

public class ExceptionUtils {
	
	public static void checkBlankOrUndefined(Object value,String msg) throws Exception {
		checkBlankOrUndefined(value,msg,(Object[])null);
	}
	
	/**
	 * format("this is {} for {}", "a", "b") =》 this is a for b
	 * @param value 被检查的值
	 * @param msg 错误消息
	 * @param params 消息参数
	 */
	public static void checkBlankOrUndefined(Object value,String msg,Object... params) throws Exception {
		if(ObjectUtil.isEmpty(value) || StrUtil.isBlankOrUndefined(StrUtil.toString(value))) {
			throwException(null,msg,params);
		}
	}

	/**
	 * format("this is {} for {}", "a", "b") =》 this is a for b
	 * @param ex 上级异常 可以为空
	 * @param msg 错误消息
	 * @param params 消息参数
	 */
	public static void throwException(Exception ex,String msg,Object... params) throws Exception {
		if(params!=null&&params.length!=0)
			msg=StrUtil.format(msg, params);
		if(ex!=null)
			throw new Exception(msg,ex);
		else
			throw new Exception(msg);
	}

	/**
	 * 获取异常的详细报错
	 * @param ex
	 * @return
	 */
	public static String getDetailInfo(Throwable ex){
		StringBuilder msg=new StringBuilder();
		msg.append(ex.getMessage()+"\r\n");
		if(ex.getCause()!=null){
			msg.append("错误原因:\r\n");
			msg.append(ex.getCause().getMessage()+"\r\n");
			if(ex.getCause() instanceof InvocationTargetException){
				final InvocationTargetException cause = (InvocationTargetException) ex.getCause();
				msg.append("调用目标错误:\r\n");
				msg.append(cause.getTargetException().getMessage());
			}
		}
		return msg.toString();
	}

	/**
	 * 获取异常的堆栈信息
	 * @param e
	 * @return
	 */
	public static String getStackTraceAsString(Exception e) {
		// 使用 StringWriter 和 PrintWriter 来捕获堆栈信息
		java.io.StringWriter stringWriter = new java.io.StringWriter();
		java.io.PrintWriter printWriter = new java.io.PrintWriter(stringWriter);

		// 将堆栈信息打印到 PrintWriter 中
		e.printStackTrace(printWriter);

		// 转换为字符串并返回
		return stringWriter.toString();
	}
}
